﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Drawing;
using Intorise.Common;

namespace Model
{
    public partial class Player
    {
        Timer tradeTimer = null;
        ManualResetEvent tradeEvent = new ManualResetEvent(true);
        static string[] needTradeNames = new string[] { "生命宝石", "灵魂宝石", "祝福宝石", "玛雅之石", "初级坐骑丹" };
        static string[] needTradBeginName = new string[] { "兑_" };

        /// <summary>
        /// 开始交易定时器
        /// </summary>
        private void StartTradeTimer()
        {
            if (tradeTimer != null) { return; }
            if (this.Master == null)
            {
                ConsoleBLL.WriteLineError("仓库号没有配置，无法开始自动交易程序.."); return;
            }
            if (tradeTimer == null)
            {
                tradeTimer = new Timer(TradeMethod, null, 1000 * 60 * 30, 1000 * 60 * 30);//30分钟进行一次交易
            }
        }

        private void TradeMethod(object o)
        {
            ConsoleBLL.WriteLineWaring(this + "开始执行交易程序..");
            StopRunScript(PlayerStatusEnum.交易物品);
            try
            {
                Items.Clear();
                CleanPackage();
                Thread.Sleep(3000);
                this.Status = PlayerStatusEnum.交易物品;

                #region 交易
                ConsoleBLL.WriteLineInfo(this + string.Format("前往仓库号所在地进行交易..."));
                Transmit(Master.CurrentMap);    //移动到仓库号所在地图
                Thread.Sleep(1000);

                Change(1);

                Thread.Sleep(1000);
                //发送交易邀请
                tradeEvent.Reset();
                InviteTrade(Master.ID);
                //等待对方同意(60秒超时)
                if (!tradeEvent.WaitOne(1000 * 20))
                {
                    ConsoleBLL.WriteLineError(this + string.Format("等待{0}同意交易超时，交易取消！", Master.ID)); InviteTrade(Master.ID);//return;
                    goto end;
                }
                //Thread.Sleep(2000);
                //放入物品并锁定
                //lock (Items)
                //{

                List<Thing> things = new List<Thing>(6);

                lock (Items)
                {
                    foreach (var t in Items)
                    {
                        foreach (var n in needTradBeginName)
                        {
                            if (t.Name.StartsWith(n))
                            {
                                things.Add(t); break;
                            }
                        }
                        if (things.Count > 5)
                        {
                            break;
                        }
                        if (needTradeNames.Contains(t.Name))
                        {
                            things.Add(t);
                        }
                        if (things.Count > 5)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < things.Count; i++)
                {
                    PutItem(things[i], (short)(i + 1));
                    Thread.Sleep(200);
                }
                //}
                Thread.Sleep(200);
                //放入金币
                var datas = new byte[] { 0x00, 0x01, 0xDD, 0x5F };
                for (int i = 0; i < GoldID.Length; i++)
                {
                    datas = Tools.Contact(datas, GoldID[i]);
                }
                datas = Tools.Contact(net.GetNetworkBytes(datas.Length), datas);
                engine.SendData(datas);

                Thread.Sleep(500);
                Items.Clear();

                LockTrade();//发送锁定
                ConsoleBLL.WriteLineError(this + string.Format("{0}放入物品并锁定，等待仓库号锁定！", this));
                //等待对方锁定交易(60秒超时)
                tradeEvent.Reset();
                if (!tradeEvent.WaitOne(1000 * 20))
                {
                    ConsoleBLL.WriteLineError(this + string.Format("等待{0}锁定交易超时，交易取消！", Master.ID)); //return;
                }

                AffirmTrade();//发送确认
                Thread.Sleep(1000);
                #endregion
            end:
                ConsoleBLL.WriteLineInfo(string.Format("{0}交易已完成", this));
                NeedTrade = false;
            }
            catch (Exception ex)
            {
                GameHelper.Handle(ex);
            }
            finally
            {
                GameHelper.RunGameThread(PlayAutoFight);
            }
        }

        /// <summary>
        /// 邀请编号为id的玩家交易
        /// </summary>
        /// <param name="id"></param>
        private void InviteTrade(long id)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x59 }, net.GetNetworkBytes(id), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 同意交易邀请
        /// </summary>
        /// <param name="id"></param>
        private void AgreeTrade()
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5A }, net.GetNetworkBytes(this.ID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 摆放物品
        /// </summary>
        /// <param name="item">物品</param>
        /// <param name="index">位置</param>
        private void PutItem(Thing item, short index)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5D }, net.GetNetworkBytes(index), net.GetNetworkBytes(item.InstanceID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 锁定交易
        /// </summary>
        private void LockTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x01, 0x01 });
        }

        /// <summary>
        /// 确认交易
        /// </summary>
        private void AffirmTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x02, 0x01 });
        }

        //#region 交易处理器



        ///// <summary>
        ///// 确认交易处理器
        ///// </summary>
        ///// <param name="x"></param>
        ///// <returns></returns>
        //private bool ProcessAffirmTrade(Message x)
        //{
        //    GameHelper.Run(x, r =>
        //    {
        //        var item = new AffirmTradeMsg(x.Data);
        //        if (this.ID == Player.Master.ID)//当前号是仓库号，收到挂机号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到挂机号{0}已确认交易", item.InvitePlayerID));
        //            tradeEvent.Set();
        //        }
        //        else//当前号是挂机号，收到仓库号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到仓库号{0}已确认交易，交易已完成", Player.Master));
        //        }
        //    });
        //    return true;
        //}
        //#endregion
    }
}
